import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/bocchi.dart';
import 'package:wallpaper/components/input/my_search_input.dart';
import 'package:wallpaper/components/video/video_list.dart';
import 'package:wallpaper/model/random_video_base.dart';

class BocchiVideo extends StatefulWidget {
  const BocchiVideo({super.key});

  @override
  State<BocchiVideo> createState() => _BocchiVideoState();
}

class _BocchiVideoState extends State<BocchiVideo>
    with SingleTickerProviderStateMixin {
// 1. 状态变量优化：用 final 修饰集合（只改内容不改引用），常量用 final
  final List<VideoBaseInfo> videoList = [];
  bool isLoading = false;
  int page = 1;
  final int pageSize = 20;
  int totalPages = 0;
  String order = 'DESC'; // DESC: 最新 ASC: 最早
  final TextEditingController controller = TextEditingController();
  late AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    getBocchiImgs();

// 初始化动画控制器（保留原动画逻辑）
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
      value: 0.0, // 初始对应 DESC 状态
    );
  }

  Future<void> getBocchiImgs() async {
    if (!mounted || isLoading) return;
    setState(() {
      isLoading = true;
    });
    try {
      var res = await getBocchiWallpapers(
        page: page,
        limit: pageSize,
        q: controller.text,
        type: 3,
        order: order,
      );
      totalPages = res.data['data']['pagination']['totalPages'];
      List bocchi = res.data['data']['items'];

      // 2. 批量添加数据：减少 setState 调用次数（原循环内 setState 会频繁触发重建）
      final newVideos = <VideoBaseInfo>[];
      for (var i = 0; i < bocchi.length; i++) {
        newVideos.add(VideoBaseInfo(
          cover: bocchi[i]['cover'],
          url: bocchi[i]['url'],
          tag: bocchi[i]['tags'],
        ));
      }

      setState(() {
        videoList.addAll(newVideos);
      });
    } catch (e) {
      debugPrint(' 加载视频错误: $e');
    } finally {
      if (mounted) {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

// 3. 提取排序切换逻辑：独立方法，避免构建方法内写复杂逻辑
  void _switchOrder() {
    setState(() {
      if (order == 'DESC') {
        order = 'ASC';
        _animationController.forward();
        BotToast.showText(text: ' 最早 ');
      } else {
        order = 'DESC';
        _animationController.reverse();
        BotToast.showText(text: ' 最新 ');
      }
      videoList.clear();
      page = 1;
      totalPages = 0;
    });
    getBocchiImgs();
  }

// 4. 提取搜索提交逻辑：统一处理，减少代码冗余
  void _handleSearchSubmitted(String value) {
    FocusScope.of(context).unfocus(); // 简洁失焦
    page = 1;
    videoList.clear();
    getBocchiImgs();
  }

  @override
  void dispose() {
    controller.dispose();
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;

// 5. 全局重绘隔离：避免页面其他部分因局部状态变化重绘
    return RepaintBoundary(
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        floatingActionButton: FloatingActionButton(
          onPressed: _switchOrder, // 调用提取后的排序方法
          elevation: 6,
          child: AnimatedIcon(
            icon: AnimatedIcons.home_menu,
            progress: _animationController,
            color: theme.onSurface,
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
        appBar: AppBar(
          title: const Text(''),
          toolbarHeight: 0,
          elevation: 0,
          leading: null,
          backgroundColor: theme.primaryContainer,
          surfaceTintColor: theme.primaryContainer,
        ),
        body: Column(
          children: [
            // 6. 搜索框独立封装：核心优化！隔离搜索框状态变化范围
            const RepaintBoundary(
              child: _SearchInputWrapper(),
            ),
            Expanded(
              child: VideoList(
                videoList: videoList,
                isLoading: isLoading,
                onImageBottomLoading: () {
                  if (page < totalPages) {
                    page++;
                    getBocchiImgs();
                  }
                },
                onImageListRefresh: () {
                  page = 1;
                  videoList.clear();
                  getBocchiImgs();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 7. 搜索框独立组件：仅负责搜索框渲染，状态通过父组件获取
class _SearchInputWrapper extends StatelessWidget {
  const _SearchInputWrapper();

  @override
  Widget build(BuildContext context) {
// 通过上下文获取父组件状态（安全且不破坏封装）
    final parentState = context.findAncestorStateOfType<_BocchiVideoState>()!;

    return MySearchInput(
      controller: parentState.controller,
      onSubmitted: (v) => parentState._handleSearchSubmitted(v),
    );
  }
}
